﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Tapeer
{
    class Animation
    {
        private Texture2D m_texture;
        private Rectangle[] m_frames;
        
        public string Resouce { get; set; }
        public int Columns { get; set; }
        public int Rows { get; set; }
        public int FrameInterval { get; set; }
        public bool LeftToRight { get; set; }
        public bool AutoRepeat { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public Game Game { get; set; }
        public Vector2 Position { get; set; }
        private int m_currentFrame;
        private int m_timeSizeLastFrame;

        public void Reset()
        {
            m_currentFrame = 0;
        }

        public Animation(Game game, string resource, int rows = 1,int frameInterval = 60, int columns = 1)
        {
            Game          = game;
            Resouce       = resource;
            Columns       = columns;
            Rows          = rows;
            Position      = Vector2.Zero;
            FrameInterval = frameInterval;
            AutoRepeat    = true;
        }

        public void LoadContent()
        {
            m_texture = Game.Content.Load<Texture2D>(Resouce);
            var cellCount = Columns*Rows;

            double incx = m_texture.Width/(double) Columns;
            double incy = m_texture.Height/(double) Rows;

            m_frames = new Rectangle[cellCount];
            for (var i = 0; i < Rows; i++)
            {
                for (var j = 0; j < Columns; j++)
                {
                    var index = (i*Columns) + j;
                    m_frames[index] = new Rectangle((int)(incx * j), (int)(incy * i),Width,Height);
                }                
            }
        }

        public void Update(GameTime gameTime)
        {
            m_timeSizeLastFrame += gameTime.ElapsedGameTime.Milliseconds;
            if (m_timeSizeLastFrame > FrameInterval)
            {
                m_timeSizeLastFrame -= FrameInterval;
                m_currentFrame++;

                if (m_currentFrame >= m_frames.Length)
                    m_currentFrame = (AutoRepeat ? 0 : m_frames.Length - 1);
            }
        }

        public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
        {
            if (LeftToRight)
                spriteBatch.Draw(m_texture, Position, m_frames[m_currentFrame], Color.White, 0, Vector2.Zero,
                                 Vector2.One, SpriteEffects.FlipHorizontally, 0);
            else
                spriteBatch.Draw(m_texture, Position, m_frames[m_currentFrame], Color.White);
        }

        public void UnloadContent()
        {            
        }
    }

}
